package com.graph;

import java.util.HashMap;
import java.util.HashSet;

public class Solution1319 {
    int[] father;
    int count;
    public int makeConnected(int n, int[][] connections) {
        father = new int[n];
        for (int i = 0; i < n; i++) {
            father[i] = i;
        }
        count = n;
        int extra = 0;
        for (int[] connection : connections) {
            if (same(connection[0], connection[1])) {
                extra++;
            } else {
                join(connection[0], connection[1]);
            }
        }
        if (count - 1 > extra) return -1;
        return count - 1;
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public int find(int x) {
        if (x == father[x]) return x;
        father[x] = find(father[x]);
        return father[x];
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
        count--;
    }
}
